<template>
  <div class="after-video-uploaded">
    <video-uploading v-if="uploadStatus==='uploading'" :progress="progress"></video-uploading>
    <video-upload-status v-if="uploadStatus!=='uploading'" :status="uploadStatus"
                         @reupload="checkUpload"></video-upload-status>
    <common-form :formConfig="formConfig" @input="onFormInput"></common-form>
    <div class="form-operation">
      <button class="form-btn btn-primary" :class="{'btn-disable':pushing}" @click="doSubmit(1)">发布</button>
      <button class="form-btn" @click="doSubmit(0)" v-if="!hasPublish">存草稿</button>
      <button class="form-btn" :class="{'btn-disable':pushing}" @click="doPreview">预览</button>
      <button class="form-btn" :class="{'btn-disable':pushing}" @click="doCancel">取消</button>
    </div>
  </div>
</template>

<script>
  import VideoUploading from './videoUploading.vue';
  import VideoUploadStatus from './videoUploadStatus.vue';
  import CommonForm from '../../../../form/CommonForm.vue';

  export default {
    name: 'AfterVideoUploaded',
    components: {
      "video-uploading": VideoUploading,
      "video-upload-status": VideoUploadStatus,
      "common-form": CommonForm
    },
    computed: {
      formConfig() {
        let inputs = this.formInputs;
        let formConfig = [inputs.title, inputs.desc, inputs.cover, inputs.type];

        return formConfig.map((config) =>{
          config.value = this.tempData[config.name] || config.value;
          return config;
        });
      },
      progress() {
        return this.$store.state.publishMedia.progress;
      },
      uploader() {
        return this.$store.state.publishMedia.uploader;
      },
      uploadStatus() {
        return this.$store.state.publishMedia.status;
      },
      pushing() {
        return this.$store.state.publishMedia.pushing;
      },
      tempData() {
        return this.$store.state.publishMedia.editingVideo;
      },
      formInputs() {
        return {
          title: {
            name: 'title',
            title: '视频标题',
            desc: '请输入视频标题，4-44个字符',
            require: true,
            type: 'text',
            extra: {
              placeHolder: '4-44个字符',
              limit: [4, 44, 1]
            },
            value: this.tempData.title
          },
          desc: {
            name: 'description',
            title: '视频简介',
            desc: '请输入视频描述，20-2000个字符',
            require: true,
            type: 'textarea',
            extra: {
              placeHolder: '20-2000个字符',
              limit: [20, 2000]
            },
            value: this.tempData.description
          },
          cover: {
            name: 'imageUrl',
            title: '视频封面',
            require: true,
            type: 'cover',
            value: this.tempData.imageUrl,
            extra: {
              fileDesc: '建议尺寸686*300,大小不超过2M',
              maxFileSize: 2 * 1024 * 1024,
              width: 686,
              height: 300,
              viewWidth: 154,
              viewHeight: 86
            }
          },
          type: {
            name: 'previewAllowed',
            title: '是否试读',
            desc: '',
            require: true,
            type: 'radio',
            extra: {
              radio: [{
                key: 1,
                text: '允许',
                checked: true
              }, {
                key: 0,
                text: '禁止',
                checked: true
              }]
            },
            value: this.tempData.previewAllowed
          }
        };
      },
      specialColumnId() {
        return this.$route.params.id;
      },
      coursePacketId() {
        return this.$route.params.issue;
      },
      hasPublish() {
        let status = this.$store.state.publishMedia.editingVideo.status;
        if (!status) {
          return false;
        }
        return status == 2;
      }
    },
    data() {
      return {
        formData: {},
        validate: {},
        previewPopup: null
      };
    },
    methods: {
      checkUpload() {
        if (this.uploadStatus === 'uploading' && this.uploader)
          this.uploader.promise.then((res) =>{
            try {
              res = window.JSON.parse(res)
            } catch (e) {}
            if (this.$store.state.publishMedia.status !== 'standby') {
              if (res.code === 200) {
                this.$store.dispatch('videoEndUpload');

                this.formData.vid = res.data.vid;
                this.formData.type = "video";
                this.formData.mediaUrl = res.data.url;

                this.$store.dispatch('videoSetTempData', this.formData);
              }
              else {
                this.$store.dispatch('videoEndUpload', 'error');
                this.$store.dispatch('alert', res.message);
              }
            }
          }, (res) =>{
            if (this.$store.state.publishMedia.status !== 'standby') {
              this.$store.dispatch('alert', res.message || '抱歉，上传失败>_<');
              this.$store.dispatch('videoEndUpload', 'error');
            }
          });
      },
      onFormInput({ formData, validate, name, value }) {
        Object.assign(this.formData, formData);
        this.validate = validate;//console.log(this.formData)
        this.$store.dispatch('videoSetTempData', this.formData);
      },
      doSubmit(flagType) {//0|保存,1|发布
        if (this.uploadStatus !== 'uploaded') {
          this.$store.dispatch('alert', '请等待视频上传完毕~');
          return;
        }
        for (let i = 0; i < this.formConfig.length; i++) {
          let config = this.formConfig[i];
          let validate = this.validate[config.name];
          if (!validate.ok) {
            this.$store.dispatch('alert', `${config.title}${validate.info}`);
            return false;
          }
        }

        this.formData.coursePacketId = this.coursePacketId;
        if (this.formData.id && !this.formData.vid) {//修改
          this.formData.vid = this.formData.rid;
        }

        this.formData.flag = flagType;
        this.$store.dispatch('videoSetTempData', this.formData);
        this.$store.dispatch('videoSubmit').then(() =>{
          this.$store.dispatch('alert', '提交成功！');
          this.$store.dispatch('mediaClearTempData');

          this.$router.push(`/columns/journal/${this.specialColumnId}/${this.coursePacketId}/list`);
        }, ((res) =>{
          this.$store.dispatch('alert', res.message ? res.message : '抱歉，提交失败>_<');
        }));
      },
      doPreview() {
        let delay = 0;
        if (!this.previewPopup || this.previewPopup.closed) {
          let viewWidth = 900;
          let viewHeight = 800;
          let offsetLeft = (window.screen.availWidth - viewWidth) / 2;
          let offsetTop = (window.screen.availHeight - 30 - viewHeight) / 2;
          let url = C_OPEN + '/mob/static/column/preview.htm?type=2&project=static&id=' + this.formData.id;
          this.previewPopup = window.open(url, "", `height=${viewHeight},width=${viewWidth},top=${offsetTop},left=${offsetLeft},status=no,toolbar=no,menubar=no,location=no`);
          delay = 1500;
        }
        setTimeout(() =>{
          this.previewPopup.postMessage({
            id: this.formData.id,
            title: this.formData.title,
            mediaUrl: this.formData.mediaUrl,
            description: this.formData.description,
            imageUrl: this.formData.imageUrl,
            previewAllowed: this.formData.previewAllowed
          }, C_OPEN);
          this.previewPopup.focus();
        }, delay);
      },
      doCancel() {
        if (this.$store.getters.hasTempVideoDate) {
          this.$store.dispatch('confirm', '您已输入的内容将会丢失，是否确定？').then(this.doLeave, () =>{});
        }
        else {
          this.doLeave();
        }
      },
      doLeave() {
        // if (!this.isEdit) {
        try {
          this.$store.state.publishMedia.request.abort();
        } catch (e) {}
        this.$store.dispatch('mediaClearTempData');
        this.previewPopup.close();
        // }else{
        this.$emit('cancel');
        // }
      }
    },
    created() {
      this.checkUpload();
      Object.assign(this.formData, this.tempData);
    }
  };
</script>

<style lang="less" rel="stylesheet/less">
</style>
